<?php
require_once 'PerformanceMetrics.php';
require_once 'PerformanceMetricsLocations.php';

class Locations extends HTech_Db_Table implements Emms_Interface_Performance, Emms_Interface_Geo
{
    
    protected $_name    = 'view_locations';
    protected $_primary = 'LocationId';
     
    protected $_dependentTables = array('LnkLocationsPrograms');
    protected $_lnkTables = array('LnkLocationsPrograms' => 'ProgramId');

    protected function _setGridMetadata()
    {
        $this->_gridMetadata['title'] = $this->translate("Locations");
        $this->_gridMetadata['onClick'] = 'admin.location.view';
        $this->_gridMetadata['headers'] = array
            (
                array('Code',       60, $this->translate("Code"),       'String'),
                array('Category',  100, $this->translate("Category"),   'String'),
                array('ShortName', 120, $this->translate("Short name"), 'String'),
                array('Name',      200, $this->translate("Name"),       'String'),
                array('Tel1',      100, $this->translate("Tel1"),       'String'),
                array('Tel2',      100, $this->translate("Tel2"),       'String'),
                array('Fax',       100, $this->translate("Fax"),        'String'),
                array('Address',   500, $this->translate("Address"),    'String'),
                array('Comments',  500, $this->translate("Comments"),   'String')
            );
        return $this;
    }  
    
    protected function _setRecordDependentRows()
    {
        $this->_record->r = (object) array('programs' => null);
        $this->_record->r->programs = $this->_record->d->findManyToManyRowset('Programs','LnkLocationsPrograms'); 
        array_walk($this->_record->r->programs->toArray(), array($this, '_setRecordLnkData'), array('LnkLocationsPrograms', 'ProgramId'));  
    }
            
    protected function _setRecordPerformance() 
    {
        $this->_record->p = $this->getPerformance($this->_record->d, new Zend_Date());
    }
    
    public function getPoints($id)
    {   
        $communities = Zend_Registry::get('db')->fetchAll(sprintf('
            select Community title, Latitude lat, Longitude lng, "%s" category 
            from view_communities 
            where LocationId = %s or ParentLocationId = %s or SuperParentLocationId = %s', self::EMMS_COMMUNITY, $id, $id, $id));
        $locations = Zend_Registry::get('db')->fetchAll(sprintf('
            select l.Name title, l.Latitude lat, l.Longitude lng, "%s" category
            from locations l
            left join locations p on p.LocationId = l.ParentLocationId
            left join locations sp on sp.LocationId = p.ParentLocationId
            where l.LocationId = %s or p.LocationId = %s or sp.LocationId = %s', self::EMMS_LOCATION, $id, $id, $id));        
        return array_merge($communities, $locations);
    }
    
    public function getPerformanceCharts(Zend_Db_Table_Row $row)
    {   
        return array(
            'title' => $row['Name'],
            'subtitle' => self::translate('Performance charts'),
            'params' => array(
                'p1' => 'LocationId',
                'v1' => $row['LocationId'],
                'p2' => 'ShortName',
                'v2' => $row['ShortName']),
            'charts' => array(
                'day' => array(
                    'chartId' => 'LocationPerformanceDay',
                    'chartData' => '/admin/chart/performance/Mode/Day/Subject/Location/id/' . $row['LocationId'],
                    'chartSizeX' => 350,
                    'chartSizeY' => 320),
                'week' => array(
                    'chartId' => 'LocationPerformanceWeek',
                    'chartData' => '/admin/chart/performance/Mode/Week/Subject/Location/id/' . $row['LocationId'],
                    'chartSizeX' => 200,
                    'chartSizeY' => 320),
                'month' => array(
                    'chartId' => 'LocationPerformanceMonth',
                    'chartData' => '/admin/chart/performance/Mode/Month/Subject/Location/id/' . $row['LocationId'],
                    'chartSizeX' => 600,
                    'chartSizeY' => 320)
            )
        );
    }
    
    public function getPerformance(Zend_Db_Table_Row $row, Zend_Date $date, $options = array())
    {
        $row = $row; $date = $date; $options = $options;
        
        $ps = array();
        $pc = array();
        
        $pf = Zend_Registry::get('db')->query("select * from performance_data where Date = curdate() and LocationId = ?", 
                array($row['LocationId']))->fetchAll();
        
        foreach($pf as $metric) {
            $ps[$metric->Metric] = $metric->Value;
            $pc[$metric->Metric] = $metric->Color;
        }
        $ps['c'] = (object) $pc;
        return (object) $ps;
    }
      
    static function getLocationOptions($id = 0)
    {
        if(!$id)            
            return array('' => '--- ' . self::translate('Select location')) + 
                Zend_Registry::get('db')->fetchPairs("select LocationId, Name 
                    from view_locations order by Name");
        return array();
    }
    
    static function getParentLocationOptions($id = 0,$cat = "")
    {
        if ($cat == 'Center') return array();
        $db = Zend_Registry::get('db');
        if ($cat) {
            return $db->fetchPairs(sprintf("select LocationId, Name from locations where 
                LocationId != '%s' and Category = if('%s'='Branch','Center','Branch')", $id, $cat));
        }
        if ($id) {
            return $db->fetchPairs(sprintf("select f.LocationId, f.Name from locations l, locations p, locations f 
                where l.LocationId = '%s' and p.LocationId = l.ParentLocationId and f.Category = p.Category", $id)); 
        }
        return array();
    }
}